/* =========================================
 *      消息转发子服务 --- 服务器搭建 
 * =========================================*/

#include "transmite_server.hpp"
#include "logger.hpp"
#include <bits/types/FILE.h>
#include <gflags/gflags.h>

DEFINE_bool(run_mode, false, "程序的运行模式: false-调试 true-发布");
DEFINE_string(log_file, "", "指定日志的输出文件");
DEFINE_int32(log_level, 0, "指定日志输出等级");

DEFINE_string(registry_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(instance_name, "/transmite_service/instance", "当前服务的实例名称");
DEFINE_string(access_host, "127.0.0.1:8004", "当前实例的外部访问地址");

DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(user_service, "/service/user_service", "监控的子服务名称");

DEFINE_int32(listen_port, 8004, "Rpc服务器监听端口");
DEFINE_int32(rpc_timeout, -1, "Rpc连接空闲的超时上限(-1表无限空闲)");
DEFINE_int32(rpc_threads, 1, "Rpc的IO线程数");

DEFINE_string(mysql_host, "127.0.0.1", "mysql服务器地址");
DEFINE_int32(mysql_port, 0, "mysql服务器端口");
DEFINE_string(mysql_db, "chat_system", "mysql默认数据库名称");
DEFINE_string(mysql_user, "root", "mysql用户名");
DEFINE_string(mysql_pswd, "weng9244", "mysql密码");
DEFINE_string(mysql_cset, "utf8", "mysql客户端字符集");
DEFINE_int32(mysql_max_pool, 3, "mysql连接池最大连接数量");

DEFINE_string(mq_user, "root", "rabbitMQ服务器访问用户名");
DEFINE_string(mq_pswd, "weng9244", "rabbitMQ服务器访问密码");
DEFINE_string(mq_host, "127.0.0.1:5672", "rabbitMQ服务器访问地址");
DEFINE_string(mq_msg_exchange, "msg_exchange", "离线消息的发布交换机名称");
DEFINE_string(mq_msg_queue, "msg_queue", "离线消息的发布队列名称");
DEFINE_string(mq_msg_binding_key, "msg_queue", "离线消息的交换机-队列绑定信息");

int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    shared::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    im_server::MsgTransmitServerBuilder msgTransmitServerBuilder;
    msgTransmitServerBuilder.makeMysqlObject(
        FLAGS_mysql_user, FLAGS_mysql_pswd, FLAGS_mysql_host, 
        FLAGS_mysql_db, FLAGS_mysql_cset, FLAGS_mysql_port, FLAGS_mysql_max_pool
    );
    msgTransmitServerBuilder.makeRabbitMQObject(
        FLAGS_mq_user, FLAGS_mq_pswd, FLAGS_mq_host, 
        FLAGS_mq_msg_exchange, FLAGS_mq_msg_queue, FLAGS_mq_msg_binding_key
    );
    msgTransmitServerBuilder.makeRpcSvrDiscoverer(      // 构造服务发现对象, 进行服务监听
        FLAGS_registry_host, FLAGS_base_service, FLAGS_user_service
    );
    msgTransmitServerBuilder.makeRpcSvrRegistrant(     // 构造服务注册对象, 进行服务注册
        FLAGS_registry_host, FLAGS_base_service + FLAGS_instance_name, FLAGS_access_host
    );
    msgTransmitServerBuilder.makeRpcServer(FLAGS_listen_port, FLAGS_rpc_timeout, FLAGS_rpc_threads);  // 构造rpc服务器
    im_server::MsgTransmitServerPtr msgTransmitServer = msgTransmitServerBuilder.build();
    msgTransmitServer->start();  
    return 0;
}